package unclassified.medium;

import java.util.LinkedList;
import java.util.Queue;

public class ColoringABorder_1034 {

    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        int m = grid.length, n = grid[0].length;
        int[][] res = new int[m][n];
        boolean[][] visited = new boolean[m][n];

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{row, col});
        visited[row][col] = true;

        while(!queue.isEmpty()) {
            int[] poll = queue.poll();
            int i = poll[0], j = poll[1];
            int flag = 0;
            for (int[] dir : dirs) {
                int x = i + dir[0], y = j + dir[1];
                if (x >= 0 && x < m && y >= 0 && y < n){
                    if (grid[x][y] == grid[row][col]) {
                        flag++;
                        if (!visited[x][y]) {
                            queue.offer(new int[]{x, y});
                            visited[x][y] = true;
                        }
                    }
                }
            }
            res[i][j] = flag == 4 ? grid[i][j] : color;
        }
        for (int i = 0; i < res.length; i++) {
            for (int j = 0; j < res[i].length; j++) {
                if (!visited[i][j])
                    res[i][j] = grid[i][j];
            }
        }
        return res;
    }

    /**
     * [[1,2,1,2,1,2],[2,2,2,2,1,2],[1,2,2,2,1,2]]
     * 1
     * 3
     * 1
     * @param args
     */
    public static void main(String[] args) {
        ColoringABorder_1034 cb = new ColoringABorder_1034();
        cb.colorBorder(new int[][]{{1,2,1,2,1,2}, {2,2,2,2,1,2}, {1,2,2,2,1,2}}, 1, 3, 1);

    }
}
